package com.demo.utils;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringUtils {
    public static void listAllBeans(ApplicationContext context) {
        // 获取所有bean名称
        String[] beanNames = context.getBeanDefinitionNames();

        System.out.println("Spring容器中定义的bean列表：");
        System.out.println("=====================================");

        //遍历所有bean，获取名称、类型、类名、是否单例等信息
        for (String beanName : beanNames) {
            System.out.println("Bean名称: " + beanName);
            System.out.println("Bean类型(实际运行时): " + context.getType(beanName).getName());

            // 获取详细的bean定义信息
            ConfigurableListableBeanFactory beanFactory =
                    ((ConfigurableApplicationContext) context).getBeanFactory();
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

            System.out.println("Bean类名(配置时声明): " + beanDefinition.getBeanClassName());
            System.out.println("是否为单例: " + context.isSingleton(beanName));
            System.out.println("-------------------------------------");
        }

        System.out.println("总计bean数量: " + beanNames.length);
    }
}
